/* eslint-disable */
// @ts-nocheck
import React, {
  useState, useEffect, useRef, useCallback,
} from 'react'

const SmoothLogViewer = () => {
  const [logs, setLogs] = useState([])
  const [isRunning, setIsRunning] = useState(false)
  const [autoScroll, setAutoScroll] = useState(true)
  const logContainerRef = useRef(null)
  const isUserScrollingRef = useRef(false)
  const scrollTimeoutRef = useRef(null)
  const logIntervalRef = useRef(null)
  const lastScrollTopRef = useRef(0)

  // 生成随机日志条目
  const generateLogEntry = useCallback(() => {
    const now = new Date()
    const timestamp = `[${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}]`

    const logTypes = [
      { type: 'info', message: '用户登录成功' },
      { type: 'info', message: '数据加载完成' },
      { type: 'info', message: '请求处理成功' },
      { type: 'warning', message: '内存使用率超过80%' },
      { type: 'warning', message: '网络延迟较高' },
      { type: 'error', message: '数据库连接失败' },
      { type: 'error', message: 'API请求超时' },
    ]

    const randomLog = logTypes[Math.floor(Math.random() * logTypes.length)]

    return {
      timestamp,
      type: randomLog.type,
      message: randomLog.message,
    }
  }, [])

  // 平滑滚动到底部
  const smoothScrollToBottom = useCallback(() => {
    if (!logContainerRef.current) return

    const container = logContainerRef.current
    const startPosition = container.scrollTop
    const targetPosition = container.scrollHeight - container.clientHeight
    const distance = targetPosition - startPosition
    const duration = 300 // 动画持续时间（毫秒）
    const startTime = performance.now()

    // 如果已经在底部或距离很小，直接设置位置
    if (Math.abs(distance) < 5) {
      container.scrollTop = targetPosition
      return
    }

    function scrollStep(currentTime) {
      const elapsed = currentTime - startTime
      const progress = Math.min(elapsed / duration, 1)

      // 使用ease-out缓动函数
      const easeProgress = 1 - Math.pow(1 - progress, 3)

      container.scrollTop = startPosition + distance * easeProgress

      if (progress < 1) {
        requestAnimationFrame(scrollStep)
      }
    }

    requestAnimationFrame(scrollStep)
  }, [])

  // 检查是否在底部
  const isAtBottom = useCallback(() => {
    if (!logContainerRef.current) return true
    const container = logContainerRef.current
    return container.scrollTop + container.clientHeight >= container.scrollHeight - 10
  }, [])

  // 处理滚动事件
  const handleScroll = useCallback(() => {
    if (!logContainerRef.current) return

    const container = logContainerRef.current
    const { scrollTop } = container
    const scrollDirection = scrollTop > lastScrollTopRef.current ? 'down' : 'up'
    lastScrollTopRef.current = scrollTop

    // 如果用户向上滚动并且不在底部，暂停自动滚动
    if (isUserScrollingRef.current && scrollDirection === 'up' && !isAtBottom()) {
      setAutoScroll(false)
    }

    // 如果用户滚动到底部，恢复自动滚动
    if (isUserScrollingRef.current && isAtBottom()) {
      setAutoScroll(true)
    }
  }, [isAtBottom])

  // 处理鼠标滚轮事件
  const handleWheel = useCallback(() => {
    isUserScrollingRef.current = true

    // 设置一个超时，在一段时间后重置isUserScrolling
    if (scrollTimeoutRef.current) {
      clearTimeout(scrollTimeoutRef.current)
    }

    scrollTimeoutRef.current = setTimeout(() => {
      isUserScrollingRef.current = false
    }, 500)
  }, [])

  // 开始日志生成
  const startLogging = useCallback(() => {
    if (logIntervalRef.current) return

    logIntervalRef.current = setInterval(() => {
      const newLog = generateLogEntry()
      setLogs((prevLogs) => [...prevLogs, newLog])
    }, 800)

    setIsRunning(true)
  }, [generateLogEntry])

  // 停止日志生成
  const stopLogging = useCallback(() => {
    if (logIntervalRef.current) {
      clearInterval(logIntervalRef.current)
      logIntervalRef.current = null
    }
    setIsRunning(false)
  }, [])

  // 清除日志
  const clearLogs = useCallback(() => {
    setLogs([])
    setAutoScroll(true)
  }, [])

  // 自动滚动效果
  useEffect(() => {
    if (autoScroll && logs.length > 0) {
      smoothScrollToBottom()
    }
  }, [logs, autoScroll, smoothScrollToBottom])

  // 组件挂载时添加事件监听器
  useEffect(() => {
    const container = logContainerRef.current
    if (container) {
      container.addEventListener('scroll', handleScroll)
      container.addEventListener('wheel', handleWheel)
    }

    // 初始化滚动位置
    if (container) {
      container.scrollTop = container.scrollHeight
    }

    // 清理函数
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll)
        container.removeEventListener('wheel', handleWheel)
      }

      if (logIntervalRef.current) {
        clearInterval(logIntervalRef.current)
      }

      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current)
      }
    }
  }, [handleScroll, handleWheel])

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d)',
      color: '#fff',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      padding: '20px',
      fontFamily: 'system-ui, sans-serif',
    }}
    >
      <h1 style={{
        textAlign: 'center', marginBottom: '20px', fontSize: '2.5rem', textShadow: '2px 2px 4px rgba(0, 0, 0, 0.5)',
      }}
      >
        平滑滚动日志查看器
      </h1>

      <div style={{
        textAlign: 'center', marginBottom: '30px', lineHeight: '1.6', fontSize: '1.1rem',
      }}
      >
        <p>使用平滑滚动技术，提供更流畅的日志查看体验</p>
        <p>向上滚动查看历史日志时自动暂停，滚动到底部时自动恢复</p>
      </div>

      <div style={{
        width: '90%',
        maxWidth: '1000px',
        background: 'rgba(0, 0, 0, 0.7)',
        borderRadius: '10px',
        padding: '20px',
        boxShadow: '0 10px 30px rgba(0, 0, 0, 0.5)',
        marginTop: '20px',
      }}
      >
        <div style={{
          display: 'flex', justifyContent: 'center', gap: '15px', marginBottom: '20px', flexWrap: 'wrap',
        }}
        >
          <button
            onClick={startLogging}
            disabled={isRunning}
            style={{
              padding: '10px 20px',
              background: isRunning ? '#555' : '#4CAF50',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: isRunning ? 'not-allowed' : 'pointer',
              fontSize: '1rem',
              transition: 'all 0.3s',
            }}
            onMouseOver={(e) => {
              if (!isRunning) {
                e.target.style.background = '#45a049'
                e.target.style.transform = 'translateY(-2px)'
              }
            }}
            onMouseOut={(e) => {
              if (!isRunning) {
                e.target.style.background = '#4CAF50'
                e.target.style.transform = 'none'
              }
            }}
          >
            开始日志
          </button>
          <button
            onClick={stopLogging}
            disabled={!isRunning}
            style={{
              padding: '10px 20px',
              background: !isRunning ? '#555' : '#f44336',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: !isRunning ? 'not-allowed' : 'pointer',
              fontSize: '1rem',
              transition: 'all 0.3s',
            }}
            onMouseOver={(e) => {
              if (isRunning) {
                e.target.style.background = '#d32f2f'
                e.target.style.transform = 'translateY(-2px)'
              }
            }}
            onMouseOut={(e) => {
              if (isRunning) {
                e.target.style.background = '#f44336'
                e.target.style.transform = 'none'
              }
            }}
          >
            停止日志
          </button>
          <button
            onClick={clearLogs}
            style={{
              padding: '10px 20px',
              background: '#2196F3',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: 'pointer',
              fontSize: '1rem',
              transition: 'all 0.3s',
            }}
            onMouseOver={(e) => {
              e.target.style.background = '#0b7dda'
              e.target.style.transform = 'translateY(-2px)'
            }}
            onMouseOut={(e) => {
              e.target.style.background = '#2196F3'
              e.target.style.transform = 'none'
            }}
          >
            清除日志
          </button>
        </div>

        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          marginBottom: '10px',
          padding: '10px',
          background: 'rgba(255, 255, 255, 0.1)',
          borderRadius: '5px',
        }}
        >
          <div>日志数量: <strong>{logs.length}</strong></div>
          <div>自动滚动: <strong style={{ color: autoScroll ? '#4CAF50' : '#ff9800' }}>{autoScroll ? '开启' : '暂停'}</strong></div>
        </div>

        <div
          ref={logContainerRef}
          style={{
            height: '400px',
            overflowY: 'auto',
            background: '#000',
            borderRadius: '5px',
            padding: '15px',
            fontFamily: 'Consolas, Monaco, "Courier New", monospace',
            fontSize: '14px',
            lineHeight: '1.5',
            position: 'relative',
            // 添加CSS平滑滚动
            scrollBehavior: 'smooth',
            // 优化滚动性能
            transform: 'translateZ(0)',
            backfaceVisibility: 'hidden',
          }}
        >
          {logs.length === 0 ? (
            <div style={{ marginBottom: '5px', padding: '5px', borderBottom: '1px solid #333' }}>
              <span style={{ color: '#4CAF50', marginRight: '10px' }}>[00:00:00]</span>
              <span style={{ color: '#64b5f6' }}>系统启动成功，等待日志输入...</span>
            </div>
          ) : (
            logs.map((log, index) => (
              <div
                key={index}
                style={{
                  marginBottom: '5px',
                  padding: '5px',
                  borderBottom: '1px solid #333',
                  animation: index === logs.length - 1 ? 'fadeIn 0.3s ease-out' : 'none',
                }}
              >
                <span style={{ color: '#4CAF50', marginRight: '10px' }}>{log.timestamp}</span>
                <span style={{
                  color:
                  log.type === 'info' ? '#64b5f6'
                    : log.type === 'warning' ? '#ffeb3b' : '#f44336',
                }}
                >
                  {log.message}
                </span>
              </div>
            ))
          )}

          {!autoScroll && (
            <div style={{
              position: 'sticky',
              bottom: '10px',
              left: '50%',
              transform: 'translateX(-50%)',
              background: '#4CAF50',
              color: 'white',
              padding: '5px 15px',
              borderRadius: '20px',
              fontSize: '0.9rem',
              display: 'inline-block',
              opacity: '0.9',
              animation: 'pulse 2s infinite',
            }}
            >
              自动滚动已暂停
            </div>
          )}
        </div>
      </div>

      {!autoScroll && (
        <div
          onClick={() => {
            setAutoScroll(true)
            smoothScrollToBottom()
          }}
          style={{
            position: 'fixed',
            right: '30px',
            bottom: '30px',
            background: '#2196F3',
            color: 'white',
            width: '50px',
            height: '50px',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            boxShadow: '0 4px 8px rgba(0, 0, 0, 0.3)',
            transition: 'all 0.3s',
            zIndex: 100,
          }}
          onMouseOver={(e) => {
            e.target.style.background = '#0b7dda'
            e.target.style.transform = 'translateY(-3px)'
          }}
          onMouseOut={(e) => {
            e.target.style.background = '#2196F3'
            e.target.style.transform = 'none'
          }}
          title="滚动到底部"
        >
          ↓
        </div>
      )}

      <style>
        {`
          @keyframes fadeIn {
            from { opacity: 0; transform: translateY(5px); }
            to { opacity: 1; transform: translateY(0); }
          }
          
          @keyframes pulse {
            0% { opacity: 0.7; }
            50% { opacity: 1; }
            100% { opacity: 0.7; }
          }
        `}
      </style>
    </div>
  )
}

export default SmoothLogViewer
